package cn.zj.logistics.controller;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.zj.logistics.pojo.MessageObject;
import cn.zj.logistics.pojo.Role;
import cn.zj.logistics.pojo.RoleExample;
import cn.zj.logistics.pojo.User;
import cn.zj.logistics.pojo.UserExample;
import cn.zj.logistics.pojo.UserExample.Criteria;
import cn.zj.logistics.service.RoleService;
import cn.zj.logistics.service.UserService;

@Controller
@RequestMapping("/admin")
public class AdminController {

	@Autowired
	private UserService userService;
	
	
	@Autowired
	private RoleService roleService;
	
	
	
	/*
	 * 认证失败跳转的方法
	 */
	@RequestMapping("/login")
	public String login(HttpServletRequest request,Model m) {
		//获取认证失败的错误信息
		String shiroLoginFailure = (String) request.getAttribute("shiroLoginFailure");
		System.out.println("shiroLoginFailure :"+shiroLoginFailure);
		if(UnknownAccountException.class.getName().equals(shiroLoginFailure)) {
			m.addAttribute("errorMsg", "亲。账号不存在！！！");
		}else if(IncorrectCredentialsException.class.getName().equals(shiroLoginFailure)) {
			m.addAttribute("errorMsg", "亲。密码错误！！！");
		}
		
		
		return "forward:/login.jsp";
	}
	
	
	
	
	
	@RequiresPermissions("admin:adminPage")
	@RequestMapping("/adminPage")
	public String adminPage() {
		
		return "adminPage";
	}
	
	
	@RequiresPermissions("admin:list")
	@RequestMapping("/list")
	@ResponseBody
	public <T> PageInfo<User> list(@RequestParam(defaultValue = "1")int pageNum,
							   @RequestParam(defaultValue = "10")int pageSize,
							   String keyword){
		
		
		
		PageHelper.startPage(pageNum, pageSize);
		
		
		UserExample example = new UserExample();
		
		
		//前台传递关键字参数不为空的时候才参与条件查询
		if(StringUtils.isNotBlank(keyword)) {
			//使用 管理员的账号和姓名搜索 OR 或者关系
			System.out.println("keyword :"+keyword);
			Criteria criteria1 = example.createCriteria();
			criteria1.andUsernameLike("%"+keyword+"%");
			
			Criteria criteria2 = example.createCriteria();
			criteria2.andRealnameLike("%"+keyword+"%");
			
			//OR关系
			example.or(criteria2);
			
			
			//根据角色名称查询 
			Criteria criteria3 = example.createCriteria();
			criteria3.andRolenameEqualTo(keyword);
			//OR关系
			example.or(criteria3);
		}
		
		
		List<User> users = userService.selectByExample(example );
		
		
		PageInfo<User> pageInfo = new PageInfo<>(users);
		
		return pageInfo;
	}
	
	@RequestMapping("/delete")
	@ResponseBody
	public MessageObject delete(Long userId) {
		
		int row = userService.deleteByPrimaryKey(userId);
		
		MessageObject mo = MessageObject.createMo(0, "删除数据失败，请联系技术人员");
		
		if(row == 1) {
			mo = MessageObject.createMo(1, "删除数据成功");
		}
		return mo;
	}
	
	
	//新增功能
	@RequestMapping("/insert")
	@ResponseBody
	public MessageObject insert(User user) {

		/*
		 * 使用 MD5对密码进行加密
		 */
		//使用UUID生成随机数 salt 盐
		String salt = UUID.randomUUID().toString().substring(0, 5);
		
		Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 3);
		//重新设置加密后的密码和salt
		user.setPassword(md5Hash.toString());
		user.setSalt(salt);
		//设置创建日期
		user.setCreateDate(new Date());
		
		int row = userService.insert(user);
		
		MessageObject mo = MessageObject.createMo(0, "新增数据数据失败，请联系技术人员");
		
		if(row == 1) {
			mo = MessageObject.createMo(1, "新增数据成功");
		}
		return mo;
	}
	
	
	
	
	//新增功能
	@RequestMapping("/update")
	@ResponseBody
	public MessageObject update(User user) {

		/*
		 * 使用 MD5对密码进行加密
		 */
		//使用UUID生成随机数 salt 盐
		String salt = UUID.randomUUID().toString().substring(0, 5);
		
		Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 3);
		//重新设置加密后的密码和salt
		user.setPassword(md5Hash.toString());
		user.setSalt(salt);
		
		
		int row = userService.updateByPrimaryKeySelective(user);
		
		MessageObject mo = MessageObject.createMo(0, "修改数据数据失败，请联系技术人员");
		
		if(row == 1) {
			mo = MessageObject.createMo(1, "修改数据成功");
		}
		return mo;
	}
	
	
	
	
	
	@RequestMapping("/adminEdit")
	public String adminEdit(Model m,Long userId) {
		
		System.out.println("userId : "+userId);
		
		if(userId !=null) {
			
			//查询出当前要修改的用户信息共享给编辑页面以供修改数据回显
			User user = userService.selectByPrimaryKey(userId);
			m.addAttribute("user", user);
		}
		
		
		//查询出所有角色共享给编辑页面，以供新增和修改的时候选择角色
		RoleExample example = new RoleExample();
		List<Role> roles = roleService.selectByExample(example);
		m.addAttribute("roles",roles);
		
		return "adminEdit";
	}
	
	
	//检查用户名是否存在
	@RequestMapping("/checkUsername")
	@ResponseBody
	public boolean checkUsername(String username) {
		
		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUsernameEqualTo(username);
		
		List<User> users = userService.selectByExample(example );
		
		return users.size() == 0 ? true :false;
		
	}
	
	
	
	
	public static void main(String[] args) {
		/*
		 * 
		 * commons-lang.x.jar
		 * 是Apache为java语言写的一个增强包
		 * 
		 * StringUtils ：字符串增强，如果判断是否为空
		 * ArraysUtils :数组增强，数组可以向list集合一样方便的增删改查操作
		 */
		
		System.out.println(StringUtils.isNotBlank(null));
		System.out.println(StringUtils.isNotBlank(""));
		System.out.println(StringUtils.isNotBlank(" "));
		System.out.println(StringUtils.isNotBlank("AA"));
		System.out.println(StringUtils.isBlank("AA"));
		
		
	}
	
	
	
	
	
}
